package com.skill.servlet;

import com.alibaba.fastjson.JSONObject;
import com.skill.dao.BaseDB;
import com.skill.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author dcf
 * @date 2019/9/27
 */
@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet.do")
public class UserServlet extends HttpServlet {

    //调用BaseDB   实例化（new）
    private BaseDB baseDB = new BaseDB();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //接收前台参数
        String method = request.getParameter("method");
        if("queryUserList".equals(method)){
            queryUserList(request,response);
        }else if("findUserById".equals(method)){
            findUserById(request,response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    private void findUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收前台参数
        String id = request.getParameter("id");
        String sql = "select * from t_user where id='"+id+"'";
        List<User> userList = baseDB.findData(sql);
        JSONObject jsonObject = new JSONObject();
        if(userList.size() == 1){
            jsonObject.put("data",userList.get(0));
            response.getWriter().print(jsonObject);
        }else {
            jsonObject.put("data","查询失败");
            response.getWriter().print(jsonObject);
        }
    }

    private void queryUserList(HttpServletRequest request, HttpServletResponse response) {
        String sql = "select * from t_user";
        List<User> userList = baseDB.findData(sql);
        try {
            //把list转化为json对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",userList);
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("打印出错");
        }
    }
}
